<?php
session_start();
header('Content-type: text/html; charset=utf-8');
require_once"lib/functions.php";
require_once"mysql.php";  
if ($_SESSION['status']!=1&&$_SESSION['status']!=24031994){
	header("Location: index.php");
}else if (!($_SESSION['user_id'])){
	header("Location: index.php");
}else{

echo'<head>
<title>Web-site</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body>
<div id="wrapper">
  <div id="header"><h1>Web-site</h1></div>
  <div id="navigation"> Navigation Here </div>
<div id="leftcolumn"><b>
	<p>Контактная информация</p></b>
	<p>Адрес: </p>
	<p>Телефон: </p>';
	//require_once"menu.html";  	
	require_once"LeftPanel.php";
	//echo"<p><a href = 'register.php'>Регистрация</a></p>";
echo'</div>  
	<div id="content">';
	echo "<h2>Введите текущие показания счетчиков</h2>";
	$res=mysql_query ("SELECT * FROM users WHERE id=".$_SESSION['user_id']) or die ("<b>Query failed:</b> " . mysql_error());
	$r=mysql_fetch_array($res);
	$res=mysql_query ("SELECT * FROM period WHERE id=(select max(id) from period)") or die ("<b>Query failed:</b> " . mysql_error());
	$r=mysql_fetch_array($res);	
	echo"<b>Текущий месяц: <font color='red'>".$r['name']."</font></b></br></br>";		
	$period=$r['id'];
	$res=mysql_query ("SELECT * FROM period WHERE id=(select max(id) from period where id <> ".$period.")") or die ("<b>Query failed:</b> " . mysql_error());

	$r=mysql_fetch_array($res);
	$lperiod=$r['id'];
	
	if (!empty($_POST))
	{
		// обрабатывае пришедшие данные функцией mysql_real_escape_string перед вставкой в таблицу БД
		$result =  mysql_query ("SELECT * FROM counters_type ORDER BY id") or die ("<b>Query failed:</b> " . mysql_error());
		while ($row = mysql_fetch_array($result)){
			$count[$row[id]]=(isset($_POST['count'.$row[id]])) ? mysql_real_escape_string($_POST['count'.$row[id]]) : '';
		};
		
	}else{
		$result =  mysql_query ("SELECT * FROM counters_type ORDER BY id") or die ("<b>Query failed:</b> " . mysql_error());
		while ($row = mysql_fetch_array($result)){
			$result1 = mysql_query ("SELECT * FROM counters WHERE period=".$period." AND counter_type=".$row[id]." AND user_id=".$_SESSION['user_id']) or die ("<b>Query failed:</b> " . mysql_error());
			if (mysql_num_rows($result1)==0){
			$count[$row[id]]=0;
			}else{
			$row1 = mysql_fetch_array($result1);
			$count[$row[id]]=$row1['counter_value'];};
		};
	};
	$result =  mysql_query ("SELECT * FROM counters_type ORDER BY id") or die ("<b>Query failed:</b> " . mysql_error());
	echo"<form action='enterValues.php' method='post'>";
	echo "<table border='1'>";
	echo "<caption>Показания счетчиков</caption>";
	echo"<tr><th>Счетчик</th><th>Прошлый месяц</th><th>Текущий месяц</th></tr>";
	while ($row = mysql_fetch_array($result)){
		$result1 = mysql_query ("SELECT * FROM counters WHERE period=".$lperiod." AND counter_type=".$row[id]." AND user_id=".$_SESSION['user_id']) or die ("<b>Query failed:</b> " . mysql_error());
		$row1 = mysql_fetch_array($result1);
		
		echo "<tr>
			<td>".$row['name']."	</td>";
			if (preg_match("|^[\d]+[\.]+[\d]*$|", $row1['counter_value']))
			{
			$rt=rtrim(rtrim($row1['counter_value'],'0'),'.');
			}else{
			$rt=$row1['counter_value'];
			};
			echo"<td align=right>".$rt."	</td>";
			if (preg_match("|^[\d]+[\.]+[\d]*$|", $count[$row[id]]))
			{
			$rt1=rtrim(rtrim($count[$row[id]],'0'),'.');
			}else{
			$rt1=$count[$row[id]];
			};
			echo"<td align=right><input align=right type='text' name='count".$row[id]."' value='".$rt1."'/></td>
		</tr>";
	};
	echo "<tr>
			<td></td>
			<td></td>
			<td align=right><input type='submit' value='Сохранить' /></td>
		</tr>";
	echo "</table>";
	echo "</form>";	
	if (!empty($_POST))
	{	
		$error = false;
		$errort = '';
		$result =  mysql_query ("SELECT * FROM counters_type ORDER BY id") or die ("<b>Query failed:</b> " . mysql_error());
		while ($row = mysql_fetch_array($result)){
			if (!preg_match("|^[\d]+[\.]?[\d]*$|",$count[$row[id]]))
			{
				$error=true;
				$errort .= 'Вы неверно ввели показания '.$row[name].'<br />';
			};
		};
		if (!$error)
		{
		$result =  mysql_query ("SELECT * FROM counters_type ORDER BY id") or die ("<b>Query failed:</b> " . mysql_error());
		while ($row = mysql_fetch_array($result)){
		$result1 = mysql_query ("SELECT * FROM counters WHERE period=".$period." AND counter_type=".$row[id]." AND user_id=".$_SESSION['user_id']) or die ("<b>Query failed:</b> " . mysql_error());
		if (mysql_num_rows($result1)==0){
		$query = "INSERT
					INTO `counters`
					SET
						`user_id`='{$_SESSION['user_id']}',
						`counter_type`='{$row[id]}',
						`counter_value`='{$count[$row[id]]}',
						`period`='{$period}'";
		}else{
		$query = "UPDATE `counters`
					SET
						`counter_value`='{$count[$row[id]]}'
					WHERE
						`user_id`='{$_SESSION['user_id']}' AND
						`counter_type`='{$row[id]}' AND						
						`period`='{$period}'";		
		};
		$sql = mysql_query($query) or die(mysql_error());
		/*echo"<script type='text/javascript'>
		alert('Ваши данные сохранены');
		</script>";*/
		
		}
		print '<h4>Ваши показания сохранены</h4>';
		
		}else{		
		print '<h4>Возникли следующие ошибки</h4>' . $errort;
		};
	};	
		
	echo'<p><h4><a href=userCabinet.php>Назад</a></h4></p>';	
echo'</div>
	<div id="rightcolumn">';
	require_once"RightPanel.php";
echo'</div>
	<div id="footer"> This is the Footer </div> 
</div>
</body>
</html>';
}
?>